<template>
	<view class="u-m-l-10 u-m-r-10 u-m-b-10 body">
		<u-toast ref="uToast" />
		<u-modal v-model="show" :content="content" title="邀请通知" show-cancel-button="true" confirm-text="确定加入"
			cancel-text="拒绝" @confirm="confirmJoin"></u-modal>
		<view class="wrap u-col-center u-row-center" v-if="!os_books">
			<view class="">
				<image src="https://account-book-cos.1900shop.online/static/images/index/cover.png" mode="widthFix">
				</image>
				<view class="u-m-l-40 u-m-r-40">
					<view class="u-text-center u-tips-color u-m-b-20">
						您还未<text class="u-type-success">创建</text>或<text class="u-type-success">加入</text>账本
					</view>
					<u-button @click="toAddBook" type="success" :custom-style="{'border-radius':'20rpx'}"
						throttle-time="500" hover-class="none">新增账本</u-button>
				</view>
			</view>
		</view>
		<view v-else>
			<!-- 看板 -->
			<view class="u-m-t-10">
				<u-sticky>
					<view class="sticky">
						<view class="u-flex u-flex-1 u-row-left u-col-center u-m-b-20" @click="accountbook">
							<u-icon name="https://account-book-cos.1900shop.online/static/images/index/book.png"
								size="36"></u-icon>
							<text
								class="u-m-l-6 u-m-r-10 u-font-bold u-font-30">{{os_books[changeBookValue].bookName || '请选择账本'}}</text>
							<u-icon name="arrow-down" size="24"></u-icon>
						</view>
						<view class="u-b-r-20 u-p-30 u-bg">
							<view class="u-flex u-row-between u-col-top">
								<view class="u-font-5">
									本月支出
								</view>
								<view class="" v-if="month && years" @click="showDate = true">
									<view class="u-font-bold u-font-30 u-flex u-row-center u-col-center">
										{{month}}月<u-icon name="arrow-down" size="16"></u-icon>
									</view>
									<view class="u-text-right" style="letter-spacing: 5rpx;">
										{{years}}
									</view>
								</view>
							</view>
							<view class="u-flex u-col-center">
								<view class="u-m-r-30">
									<u-icon
										:label="eye ? total.selectExpenditure ? Number(total.selectExpenditure).toFixed(2) : '0.00' : '******' "
										size="30" top="10" label-color="#ffffff" margin-left="2" label-size="55"
										label-pos="right" name="rmb" :custom-style="{'font-weight':'bold'}"></u-icon>
								</view>
								<view class="">
									<u-icon name="eye" size="36" @click="eye = true" v-if="!eye"></u-icon>
									<u-icon name="eye-off" size="36" @click="eye = false" v-else></u-icon>
								</view>
							</view>
							<view class="u-flex u-row-between u-col-bottom u-m-t-10">
								<view class="u-flex-wrap">
									<view class="u-m-t-20 u-font-5 u-text-center">
										本月收入
									</view>
									<view class="u-m-t-20 u-font-15">
										{{eye ? total.selectIncome ? Number(total.selectIncome).toFixed(2) : '0.00'  : '******'}}
									</view>
								</view>
								<view class="u-flex-wrap" v-if="total.budget">
									<view class="u-type-error u-m-t-20 u-font-5 u-text-center" v-if="total.isBudget">
										预算已超出
									</view>
									<view class="u-m-t-20 u-font-5 u-text-center" v-else>
										预算余额
									</view>
									<view class="u-m-t-20 u-font-15">
										{{eye ? total.selectExpenditure ? Number(total.surplusBudget).toFixed(2) : Number(total.budget).toFixed(2) || '0.00'  : '******'}}
									</view>
								</view>
								<view class="u-flex-wrap" v-if="total.budget">
									<view class="u-m-t-20 u-font-5 u-text-center" @click="showBudget = true">
										预算<u-icon class="u-m-l-10" name="setting-fill"></u-icon>
									</view>
									<view class="u-m-t-20 u-font-15" v-if="total.budget">
										{{eye ? Number(total.budget).toFixed(2)  || '0.00'  : '******'}}
									</view>
								</view>
								<view class="u-m-t-20 u-font-5 u-text-center" v-else @click="showBudget = true">
									设置本月预算<u-icon class="u-m-l-10" name="setting-fill"></u-icon>
								</view>
							</view>
						</view>
						<view class="u-m-t-30">
							<u-tabs :list="typeList" height="50" gutter="30" active-color="#18b566"
								:active-item-style="{'border-radius':'40rpx'}" font-size="35" bar-width="30"
								:current="current" @change="typeChange"></u-tabs>
						</view>
					</view>
				</u-sticky>
				<!-- 记录层 -->
				<scroll-view style="height: 500px" :scroll-y="true" :refresher-enabled="true"
					:refresher-triggered="triggered" @scrolltolower="scrolltolower" @refresherrefresh="onRefresh"
					refresher-default-style="black">
					<view v-for="(iem,index) in records" :key="index"
						v-if="typecur == -1 || (typecur == 1 && iem.disburseMoney != 0) || (typecur == 0 && iem.incomeMoney != 0)">
						<view class="u-p-20 u-flex u-row-between u-col-center u-tips-color u-bg-fff">
							<view class="u-font-12">
								{{iem.bookTime}}
							</view>
							<view class="u-flex u-font-24">
								<view class="u-flex u-m-r-20">
									<view class="u-m-r-10">
										收入
									</view>
									<view class="">
										{{Number(iem.incomeMoney).toFixed(2)}}
									</view>
								</view>
								<view class="u-flex">
									<view class="u-m-r-10">
										支出
									</view>
									<view class="u-m-r-10">
										{{Number(iem.disburseMoney).toFixed(2)}}
									</view>
								</view>
							</view>
						</view>
						<u-swipe-action bg-color="u-bg-color" :show="item.show" :index="i"
							v-for="(item,i) in iem.bookMoneyResSubVoList" :key="i"
							v-if="typecur== -1 || item.type == typecur" @click="click" @open="open(index,i)"
							:options="options">
							<view class="u-flex u-row-between u-col-center u-p-20">
								<view class="u-flex">
									<view class="u-flex u-col-center u-row-center u-header-list">
										<u-image width="60rpx" height="60rpx" :src="item.avatarUrl" mode="aspectFill"
											shape="circle"></u-image>
									</view>
									<view class="">
										<view class="u-content-color u-m-l-10">
											<text class="u-font-13">{{item.categoryName}}</text>
											<text class="u-font-10 u-p-l-10">{{item.userName}}</text>
										</view>
										<view class="u-tips-color u-m-t-10 u-m-l-10 u-font-25">
											{{item.remark}}
										</view>
									</view>
								</view>
								<view class="">
									<u-icon :label="Number(item.money).toFixed(2) || '0.00'" size="24" top="2"
										margin-left="10rpx" label-size="30" :name="item.type == 1 ? 'minus' : 'plus'"
										:custom-style="{'font-weight':'bold'}"></u-icon>
								</view>
							</view>
							<u-line color="#18b566 " border-style="dotted"></u-line>
						</u-swipe-action>
					</view>
					<view class="u-m-t-20 u-m-b-20">
						<u-loadmore :status="loadStatus" :load-text="loadText" :icon-type="iconType" />
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- 弹出层 -->
		<u-popup v-model="showBook" width="500" close-icon-color="#909399" :safe-area-inset-bottom="true"
			:mask-custom-style="{background: 'rgba(0, 0, 0, 0.8)'}" :border-radius="20" @close="accountbook('close')">
			<view>
				<view class="u-position-top u-bg-fff">
					<view class="u-flex u-row-between u-col-center u-m-l-30 u-m-t-30">
						<view class="u-font-xl u-main-color u-font-bold">
							<u-icon name="https://account-book-cos.1900shop.online/static/images/index/book.png"
								color="#55aa7f" size="38" label="点击切换账本" label-pos="right"
								label-color="#000000"></u-icon>
						</view>
						<view class="u-m-r-20">
							<u-icon name="close" color="#000000" size="30" @click="accountbook"></u-icon>
						</view>
					</view>
				</view>
				<view class="u-m-t-70"></view>
				<scroll-view scroll-y="true" :show-scrollbar="false" class="u-bg-fff">
					<view>
						<view class="u-bg-model u-p-20 u-m-20" v-for="(bo,i) in os_books" :key="i">
							<view class="u-flex u-row-between u-col-center" @click="changeBook(i)">
								<view class="u-content-color">
									<text class="u-m-r-20 u-font-10">{{bo.bookName}}</text>
								</view>
								<view class="u-content-color">
									<u-tag text="当前账本" type="warning" mode="plain" shape="circle" size="mini"
										v-if="changeBookValue == i" />
								</view>
								<view class="u-content-color">
									<u-tag text="默认账本" type="warning" mode="plain" shape="circle" size="mini"
										v-if="os_defbook == i" />
								</view>
								<view class="u-content-color">
									<u-icon name="setting" size="35"
										@click="goUrl('/pages/app/book/edit',{bookId:bo.id})"></u-icon>
								</view>
							</view>
							<view class="u-flex u-row-between u-col-center u-m-t-20" @click="changeBook(i)">
								<view class="u-header u-flex u-col-center u-row-center">
									<u-image width="70rpx" height="70rpx" :src="bo.bookAvatar" mode="widthFix"
										shape="circle"></u-image>
								</view>
								<view class="u-flex-1">
									<view class="u-flex u-row-right u-col-center u-tips-color u-font-10 u-p-b-5">
										<view class="">
											成员
										</view>
									</view>
									<view class="u-flex u-flex-1 u-row-right u-col-center">
										<view class="u-flex u-row-between u-col-center">
											<view class="overlap" v-for="(v,k) in bo.bookUserResVo.bookUserQueryVos"
												:key="k">
												<u-image width="50rpx" height="50rpx" :src="v.avatarUrl" mode="widthFix"
													shape="circle"></u-image>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="u-m-20">
							<u-button @click="goUrl('/pages/app/book/add')" type="success"
								:custom-style="{'border-radius':'20rpx'}" throttle-time="500"
								hover-class="none">新增账本</u-button>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<u-picker mode="time" v-model="showDate" :params="{year: true,month: true}" @confirm="subDate"></u-picker>
		<u-popup v-model="showBudget" mode="center" border-radius="20" :closeable="true" width="80%">
			<view class="u-m-30">
				<view class="u-flex u-row-center u-tips-color u-font-12">
					请输入本月支出预算
				</view>
				<view class="u-m-t-60 u-m-l-60 u-main-color">
					<input v-model="budgetValue" input-align="right" type="digit" placeholder="0.00" maxlength="10">
					</input>
				</view>
				<view class="u-m-t-60">
					<u-button @click="submitBudget" type="success"
						:custom-style="{'border-radius':'20rpx','font-weight':'bold','height':'100rpx','line-height':'100rpx','width':'500rpx'}"
						throttle-time="500" hover-class="none">提 交</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	let _this;
	export default {
		data() {
			return {
				typeList: [{
					name: '全部'
				}, {
					name: '收入'
				}, {
					name: '支出'
				}],
				current: 0,
				changeBookValue: 0,
				typecur: -1,
				showBook: false,
				showDate: false,
				showBudget: false,
				sheetShow: false,
				eye: true,
				records: {},
				month: '',
				years: '',
				total: {},
				option: '',
				editID: '',
				loadStatus: 'loadmore',
				iconType: 'flower',
				loadText: {
					loadmore: '轻轻下拉',
					loading: '努力加载中',
					nomore: '实在没有了'
				},
				show: false,
				options: [{
					text: '编辑',
					style: {
						backgroundColor: '#007aff'
					}
				}, {
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				bookMoneyResSubVoList: [],
				budgetValue: '',
				recordId: '',
				content: '',
				triggered: false, // 下拉是否激活
				tabDetailList: [],
				total: 0,
				pageNum: 1,
				pageSize: 1000,
				totalCount: 0,
				remarkValue: ''
			}
		},
		// 页面初次渲染完成了，但是渲染完成了，你才发送请求获取数据，显得有些慢
		onReady() {

		},
		//只加载一次，监听页面加载，其参数为上个页面传递的数据，参数类型为Object
		onLoad(e) {
			console.log("首页：" + JSON.stringify(e))
			_this = this;
			_this.pageNum = 1
			if (e) {
				_this.option = e
			}
			_this.month = this.$u.date(new Date(), 'mm')
			_this.years = this.$u.date(new Date(), 'yyyy')
			_this.records = {}
			_this.total = {}
			if (_this.option.inv == 1) {
				if (!_this.os_token) {
					_this.goReLaunchUrl('/pages/user/login?' + _this.option)
				} else {
					_this.show = true
					_this.content = '您的好友邀请您加入账本《' + _this.option.bookName + '》一起记账'
				}
			}
		},
		//监听页面显示。页面每次出现都触发，包括从下级页面点返回露出当前页面
		onShow() {
			_this.$u.vuex('os_defbook', -1)
			_this.pageNum = 1
			uni.showTabBar({
				animation: true
			})
			if (_this.os_token) {
				_this.getBook()
			} else {
				_this.goReLaunchUrl('/pages/user/login')
			}
		},
		methods: {
			// 上拉加载
			scrolltolower() {
				console.log("上拉加载")
				var num = _this.pageNum * _this.pageSize
				if (_this.totalCount > num) {
					console.log("上拉继续加载")
					_this.pageNum += 1
					_this.getRecord();
					_this.loadStatus = 'loadmore'
				}
			},
			// 自定义下拉刷新被触发
			onRefresh() {
				console.log("下拉刷新被触发")
				// 开启下拉自定义样式
				_this.triggered = true;
				if (_this.pageNum > 1) {
					_this.pageNum = _this.pageNum - 1
					//  重新调用
					_this.getRecord();
				} else {
					uni.showToast({
						title: "没有更多了",
						icon: "none",
						duration: 2000,
					});
				}
				// 1秒之后复位
				setTimeout((e) => {
					_this.triggered = false;
				}, 1000);
			},
			//新增账本
			toAddBook() {
				if (!_this.os_token) {
					uni.showModal({
						title: '登录提醒',
						content: '创建账本需要您授权，请授权登录后体验所有功能',
						confirmText: "立即登录",
						confirmColor: _this.primary,
						success: function(res) {
							if (res.confirm) {
								_this.$u.toast('即将为你跳转')
								_this.goReLaunchUrl('/pages/user/login')
							}
						}
					})
				} else {
					_this.goUrl('/pages/app/book/add')
				}
			},
			//异步获取账本信息
			async getBook() {
				uni.showLoading({
					title: '正在加载...'
				})
				await _this.$u.api.getBookList().then(res => {
					if (res) {
						_this.$u.vuex('os_books', res)
						res.forEach((item, i) => {
							if (item.defaultBook == 1) {
								_this.$u.vuex('os_defbook', i)
							}
						})
						_this.getTotal()
						_this.getRecord()
					} else {
						_this.$u.vuex('os_books', '')
						_this.$u.vuex('os_defbook', -1)
					}
					uni.hideLoading()
				}).catch(() => {
					uni.hideLoading()
				})
			},
			//切换账本
			changeBook(i) {
				_this.$u.vuex('os_selectbook', i);
				_this.changeBookValue = i
				_this.records = {}
				_this.pageNum = 1
				_this.showBook = false
				_this.getRecord()
				_this.getTotal()
			},
			//切换日期
			async subDate(e) {
				_this.month = e.month
				_this.years = e.year
				_this.getTotal()
				_this.getRecord()
			},
			//统计面板日期数据
			async getTotal() {
				await _this.$u.api.getBookDataTotal({
					bookId: _this.os_books[_this.changeBookValue].id,
					bookTime: _this.years + '-' + _this.month
				}).then((res) => {
					_this.total = res
				})
			},
			//获取对应账本数据
			async getRecord() {
				_this.loadStatus = 'loading'
				await _this.$u.api.getBookData({
					pageSize: _this.pageSize,
					pageNumber: _this.pageNum,
					bookId: _this.os_books[_this.changeBookValue].id,
					type: _this.typecur,
					bookTime: _this.years + '-' + _this.month
				}).then((res) => {
					_this.records = res.bookMoneyList.list
					_this.totalCount = res.bookMoneyList.totalCount
					var num = _this.pageNum * _this.pageSize
					if (_this.totalCount == 0) {
						_this.loadStatus = 'nomore'
					} else if (_this.totalCount <= num) {
						_this.loadStatus = 'loadmore'
					}
				})
			},
			//tab切换
			typeChange(index) {
				_this.current = index
				_this.typecur = index - 1;
				_this.getRecord();
			},
			// 列表滑块操作 如果打开一个的时候，不需要关闭其他，则无需实现本方法
			open(index, i) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				_this.bookMoneyResSubVoList = _this.records[index].bookMoneyResSubVoList;
				_this.records[index].bookMoneyResSubVoList[i].show = true;
				_this.recordId = _this.records[index].bookMoneyResSubVoList[i].id;
				_this.records.map((val, idx) => {
					_this.records[idx].bookMoneyResSubVoList.map((v, ix) => {
						if (_this.records[idx].bookMoneyResSubVoList[ix].id != _this.recordId) {
							_this.records[idx].bookMoneyResSubVoList[ix].show = false;
						}
					})
				})
			},
			//滑块列表操作 点击按钮
			click(i, optionsIndex) {
				if (optionsIndex == 0) {
					var bookMoney = _this.bookMoneyResSubVoList[i]
					bookMoney.bookId = _this.os_books[_this.changeBookValue].id
					bookMoney.bookName = _this.os_books[_this.changeBookValue].bookName
					console.log("开始跳转")
					_this.goTabbarUrl('/pages/app/bookkeeping/bookkeeping', bookMoney)
				} else {
					_this.deleteMoney()
				}
			},
			//修改预算金额
			async submitBudget() {
				if (!_this.budgetValue) {
					_this.$u.toast('请输入预算额')
					return
				}
				await _this.$u.api.editBudget({
					bookId: _this.os_books[_this.changeBookValue].id,
					budget: _this.budgetValue
				}).then((res) => {
					_this.showBudget = false
					_this.getTotal()
				})
			},
			//删除账单
			async deleteMoney() {
				await _this.$u.api.deleteMoney({
					moneyId: _this.recordId
				}).then((res) => {
					_this.getRecord()
					_this.getTotal()
				}).catch(() => {
					uni.hideLoading()
				})
			},
			//是否关闭TabBar
			accountbook(typ = '') {
				if (typ == 'close') {
					uni.showTabBar({
						animation: false
					})
					return
				}
				if (_this.showBook == false) {
					_this.showBook = !_this.showBook
					uni.hideTabBar({
						animation: false
					})
				} else if (_this.showBook == true) {
					_this.showBook = !_this.showBook
				}
			},
			//跳转到非tabbar页面
			goUrl(path, params) {
				if (params) {
					path = path + "?bookId=" + params.bookId
				}
				uni.navigateTo({
					url: path
				});
			},
			//跳转到页面，关闭其他页面
			goReLaunchUrl(path) {
				_this.$u.vuex('os_token', '');
				_this.$u.vuex('os_user', '');
				uni.reLaunch({
					url: path
				});
			},
			//跳转到tabbar页面
			goTabbarUrl(path, params) {
				if (params) {
					path = path + "?bookId=" + params.bookId + "&bookName=" + params.bookName + "&remark=" + params
						.remark + "&money=" + params.money + "&id=" + params.id + "&bookTime=" + params.bookTime
				}
				uni.reLaunch({
					url: path
				});
			},
			//加入账本
			async confirmJoin() {
				console.log('用户点击确定' + JSON.stringify(_this.option));
				let time = new Date().getTime() - _this.option.time
				if (time > 7200000) {
					_this.$u.toast('邀请码已过期')
					_this.option.inv = ''
					return
				}
				if (!_this.option.bookId) {
					_this.$u.toast('账本不存在')
					_this.option.inv = ''
					return
				}
				_this.existBookMember()
			},
			//校验用户是否过账本成员
			async existBookMember() {
				await _this.$u.api.isBookMember({
					bookId: _this.option.bookId
				}).then((res) => {
					if (res != 0) {
						_this.$refs.uToast.show({
							title: '你已经加入当前账本',
							type: 'warning',
							duration: 2000,
							position: 'top'
						})
						_this.getBook()
					} else if (res == 0) {
						_this.remarkValue = "微信用户邀请你加入《" + _this.option.bookName + "》账本"
						_this.userAddBook()
					}
				})
			},
			//加入账本
			async userAddBook() {
				await _this.$u.api.userAddBook({
					bookId: _this.option.bookId,
					remark: _this.remarkValue,
					timeStamp: _this.option.time,
				}).then((res) => {
					console.log("加入响应信息:" + res.desc)
					_this.option.inv = ''
					_this.$refs.uToast.show({
						title: '加入账本成功',
						type: 'success',
						duration: 2000,
						position: 'top'
					})
					_this.getBook()
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.body {
		background-color: $u-bg-color;
	}

	.item {
		display: flex;
		padding: 20rpx;
	}

	.sticky {
		background-color: #ffffff;
		color: #000000;
		padding: 10rpx;
	}

	.wrap {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--window-top) - var(--window-bottom));
		width: 100%;
	}

	.u-header-list {
		width: 70rpx;
		height: 70rpx;
		overflow: hidden;
		margin: 0 auto;
		border-radius: 20px;
		border: 3rpx solid $u-type-success;
	}

	.u-header {
		width: 80rpx;
		height: 80rpx;
		overflow: hidden;
		margin: 0 auto;
		border-radius: 20px;
		border: 3rpx solid $u-type-success;
	}

	.u-bg {
		background-image: linear-gradient(45deg, #39b54a, #8dc63f);
		color: #ffffff;
		border-radius: 15px;
	}

	.u-bg-fff {
		background-color: #FFFFFF;
	}

	.u-bg-model {
		background-color: #dbf1e1;
		border-radius: 15px;
	}

	.u-bg-c {
		background-color: $u-bg-color;
	}

	.u-position-top {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		z-index: 9;
	}

	.u-position-bottom {
		position: fixed;
		right: 20rpx;
		bottom: 50rpx;
		z-index: 9;
	}

	.overlap {
		margin-left: -20rpx;
	}
</style>